package com.fzdy.dataplatform.service.impl;

import com.fzdy.dataplatform.controller.api.protocol.UserKtvApi;
import com.fzdy.dataplatform.core.dao.Dao;
import com.fzdy.dataplatform.core.service.impl.BaseServiceImpl;
import com.fzdy.dataplatform.dao.KTVGroupDao;
import com.fzdy.dataplatform.dao.UserKtvDao;
import com.fzdy.dataplatform.entity.KTVGroup;
import com.fzdy.dataplatform.entity.UserKtv;
import com.fzdy.dataplatform.service.KTVGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.io.Serializable;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class KTVGroupServiceImpl extends BaseServiceImpl<KTVGroup> implements KTVGroupService {

    @Autowired
    private KTVGroupDao kTVGroupDao;
    @Autowired
    private UserKtvDao userKtvDao;

    @Override
    protected Dao getDao() {
        return kTVGroupDao;
    }

    @Override
    public Serializable insertT(KTVGroup ktvGroup, List<UserKtvApi> list) {
        int id = (int) kTVGroupDao.save(ktvGroup);
        for (UserKtvApi api : list) {
            UserKtv userKtv = new UserKtv();
            userKtv.setCreatedate(new Date());
            userKtv.setKtvgroupid(id);
            userKtv.setKid(api.getKid());
            userKtv.setSeq(api.getSeq());
            userKtv.setTDescription(api.getT_description());
            userKtvDao.save(userKtv);
        }
        return id;
    }

    @Override
    public void updateT(KTVGroup ktvGroup, List<UserKtvApi> list) {
        UserKtv userKtv = new UserKtv();
        userKtv.setKtvgroupid(ktvGroup.getId());
        List<UserKtv> oldList = userKtvDao.findByExampleEq(userKtv);
        Serializable[] ids=new Serializable[oldList.size()];
        for (int i = 0; i < oldList.size(); i++) {
            ids[i]=oldList.get(i).getId();
        }
        userKtvDao.batchDelete(ids);
        userKtvDao.flush();
        KTVGroup ktv=kTVGroupDao.get(ktvGroup.getId());
        ktv.setName(ktvGroup.getName());
        ktv.setMemo(ktvGroup.getMemo());
        kTVGroupDao.update(ktv);

        for (UserKtvApi api : list) {
            System.out.println("--------------------------"+api.getKid());
            UserKtv userKtv2 = new UserKtv();
            userKtv2.setCreatedate(new Date());
            userKtv2.setKtvgroupid(ktvGroup.getId());
            userKtv2.setKid(api.getKid());
            userKtv2.setSeq(api.getSeq());
            userKtv2.setTDescription(api.getT_description());
            userKtvDao.save(userKtv2);

        }
    }
}
